/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.notifier;

import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.mobaas.devops.Notifier;

/**
 * 邮件通知
 * @author billy zhang
 *
 */
public class EmailNotifier implements Notifier {

	@Override
	public void notify(String title, String text, Map<String, Object> config) {
		
		String smtpHost = (String)config.get("smtpHost");
		int smtpPort = (Integer)config.get("smtpPort");
		String username = (String)config.get("username");
		String password = (String)config.get("password");
		String mailFrom = (String)config.get("mailFrom");
		String mailTo = (String)config.get("mailTo");
		
		try {
			Properties props = new Properties();
	        props.put("mail.smtp.host", smtpHost);
	        props.put("mail.smtp.port", smtpPort);
	        props.put("mail.transport.protocol", "smtp");
	 
	        Session session =Session.getInstance(props);
	        MimeMessage message = new MimeMessage(session);
	 
	        Address fromAddr = new InternetAddress(mailFrom);
	        message.setFrom(fromAddr);
	 
	        String[] toArr = mailTo.split(";");
	        Address[] addrArr = new Address[toArr.length];
	        for (int i=0; i<toArr.length; i++) {
	        		addrArr[i] = new InternetAddress(toArr[i]);
	        }
	        message.setRecipients(RecipientType.TO, addrArr);
	 
	        message.setSubject(title);
	 
	        message.setText(text);
	    
	        Transport transport = session.getTransport();
	        transport.connect(smtpHost, smtpPort, username, password);
	        transport.sendMessage(message, message.getAllRecipients());
	        
	        transport.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
